package com.sihai.ehr.web.action.upload;

import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.Attendance;
import com.sihai.ehr.service.DataImportService;
import com.sihai.ehr.service.SalaryAttendanceService;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.action.ajax.AjaxCallback;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;

import java.io.File;
import java.util.Date;

/**
 * @author: wxn
 * @since: 12-7-19 下午10:05
 */
public class DataImportAction extends EHRAction{
    @BeanInject
    private DataImportService dataImportService;

    @BeanInject
    private SalaryAttendanceService salaryAttendanceService;

    private final String root_path = "upload";

    private String message;

    @Action(value = "/upload/data-import", interceptorRefs = {@InterceptorRef(value = "fileUpload"), @InterceptorRef("ehr-interceptor")})
    public String upload() throws Exception {
        if (this.uploads == null || this.uploads.length == 0) {
            AjaxCallback.failure().flush(ServletActionContext.getResponse());
        }
        String webRootPath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/");
        File f = new File(String.format("%s/%s", webRootPath, root_path));
        
        
        if (uploads != null && uploads.length > 0) {
            String filePath = null;
            if(uploads != null &&uploads.length > 0){
                File upload = uploads[0];
                String realName = uploadsFileName[0];
                String destFilePath = String.format("%s/%s_%s_%s", DateFormatUtils.format(new Date(), "yyyy-MM-dd"), System.currentTimeMillis(), RandomStringUtils.randomAlphanumeric(4), realName);
                File destFile = new File(String.format("%s/%s", f.getAbsolutePath(), destFilePath));
                FileUtils.copyFile(upload, destFile);

                String message = dataImportService.importEmployees(destFile);
                AjaxCallback.success("message", message).flush(ServletActionContext.getResponse());
            }
        }
        
        return NONE;
    }

    //add.wxn:2012.11,15
    //员工数据批量导入(见模板employee_info)
    @Action(value = "/ajax/employee-import", results = {@Result(name = "success", type = "json", params = {"root", "message"})})
    public String importEmployee() throws Exception {
        String webRootPath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/");
        String templatePath = String.format("%s/employee_data.xls", webRootPath);
        File file = new File(templatePath);
        message = dataImportService.importEmployeesForAll(file);
        return SUCCESS;
    }

    //add.wxn:2013.01.21(公共文件上传方法)
    private boolean doUpload(String saveFilePath) throws Exception{
        if (this.uploads == null || this.uploads.length == 0) {
            AjaxCallback.failure().flush(ServletActionContext.getResponse());
            return false;
        }

        if (uploads != null && uploads.length > 0) {
            if(uploads != null &&uploads.length > 0){
                File upload = uploads[0];
                File destFile = new File(saveFilePath);
                FileUtils.copyFile(upload, destFile);
                //AjaxCallback.success("message", message).flush(ServletActionContext.getResponse());
                return true;
            }
        }
        return false;
    }

    //导入考勤数据(直接读考勤数据库)
    @Action(value = "/ajax/attendance-data-import2", results = {@Result(name = "success", type = "json", params = {"root", "message"})})
    public String importAttendanceDatas2()throws Exception{
        Integer year = NumberUtils.createInteger(getParameter("year"));
        Integer month = NumberUtils.createInteger(getParameter("month"));
        message = salaryAttendanceService.importAttendanceDataFromDB(organizationId, year, month);
        return SUCCESS;
    }



    //导入考勤数据/或erp
    @Action(value = "/ajax/attendance-data-import", interceptorRefs = {@InterceptorRef(value = "fileUpload"), @InterceptorRef("ehr-interceptor")})
    public String importAttendanceDatas()throws Exception{
        return importAttendanceOrErpDatas("attendance");
    }
    @Action(value = "/ajax/attendance-erp-data-import", interceptorRefs = {@InterceptorRef(value = "fileUpload"), @InterceptorRef("ehr-interceptor")})
    public String importAttendanceErpDatas()throws Exception{
        return importAttendanceOrErpDatas("erp");
    }
    private String importAttendanceOrErpDatas(String type)throws Exception{
        String webRootPath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/");
        String saveFilePath = String.format("%s/data_import/%s", webRootPath, uploadsFileName[0]);
        if(doUpload(saveFilePath)){
            String message = null;
            Integer year = NumberUtils.createInteger(getParameter("year"));
            Integer month = NumberUtils.createInteger(getParameter("month"));
            //if(StringUtils.startsWith(uploadsFileName[0], "attendance_datas_")){
            if(StringUtils.startsWith(type, "attendance")){
                message = salaryAttendanceService.importAttendanceData(new File(saveFilePath), organizationId, year, month);
            }else if(StringUtils.startsWith(type, "erp")){
                message = salaryAttendanceService.importERPData(new File(saveFilePath), organizationId, year, month);
            }

            if(StringUtils.equals(message, "success")){
                AjaxCallback.success("message", "success").flush(ServletActionContext.getResponse());
            }else {
                AjaxCallback.failure("message", message).flush(ServletActionContext.getResponse());
            }
        }else{
            AjaxCallback.failure("message", "upload error").flush(ServletActionContext.getResponse());
        }
        return NONE;
    }

    private File[] uploads;

    private String[] uploadsFileName;

    private String[] uploadsContentType;

    public void setUploads(File[] uploads) {
        this.uploads = uploads;
    }

    public void setUploadsFileName(String[] uploadsFileName) {
        this.uploadsFileName = uploadsFileName;
    }

    public void setUploadsContentType(String[] uploadsContentType) {
        this.uploadsContentType = uploadsContentType;
    }

    public String getMessage() {
        return message;
    }
}
